const app = getApp()
Page({
  data: {
    // 有效期选项
    durationOptions: [
      {
        id: 1,
        duration: "1个月",
        price: "30",
        originalPrice: "35",
        discount: "8.5"
      },
      {
        id: 2,
        duration: "3个月",
        price: "80",
        originalPrice: "105",
        discount: "7.6"
      },
      {
        id: 3,
        duration: "12个月",
        price: "280",
        originalPrice: "420",
        discount: "6.7"
      }
    ],
	isAgreed: false,
    selectedDuration: 1, // 默认选择第一个
    selectedPrice: "30", // 默认价格
    selectedDurationText: "1个月", // 默认时长文本
	selectedContent:[],
	selectChannel:'base',
	processedList: [],//重新组装的权益数据
	vipNum:23456,
    showSuccessPopup: false, // 控制成功弹窗显示
	selectedPackageId:'',
	quanyi:['专属家庭医生服务','24小时在线咨询','用药提醒定制服务','专家预约绿色通道'],
	nowChannel:'base',
	is_vip:0
  },

  onLoad: function() {
	this.getVipLists()
	var self=this;
	app.mdInit(function (cfg,mine,area) {
		console.log(self.data.selectedContent)
		self.setData({
			cfg: cfg,
			mine:mine,
			nowChannel:mine.channel,
			is_vip:mine.is_vip,
			area:area,
			main_loaded:true,
			quanyi:cfg.family_benefits
		});		
	});
    // 初始化默认选择
  },
  //监听器
  watchQuanyiContent(){
	  let content = this.data.selectedContent
	  let bentfitSelect = false;
	  let benefitData = [];
	  if(content.length > 0){
		  this.data.quanyi.forEach((value, index, array) => {
			  console.log('索引:', index, '值:', value);
			  // array 是原数组的引用
			  if(content.includes(index.toString())){
				  bentfitSelect = true
			  }else{
				  bentfitSelect = false
			  }
			  benefitData.push({
				  selected:bentfitSelect,
				  content:value
			  });
			});
	  }
	  this.setData({
		  processedList:benefitData
	  })
	  console.log("processedList:",this.data.processedList)
  },
  toggleAgreement(e) {
    this.setData({ isAgreed: e.detail.value.includes('agree') });
  },
  viewAgreement(e) {
    wx.redirectTo({
    		url: '/vp_pz/pages/index/html?cmd=page&id=2',
    	});
  },
	getVipLists:function(){
		let that = this
		app.util.request({
		  url: 'Familydoctor/getVipPackage',
		  data: {},
			success(res){
				console.log(res.data)
				that.setData({
				  durationOptions: res.data.data,
				  selectedPrice: res.data.data[0].price,
				  selectedDurationText: res.data.data[0].duration,
				  selectedPackageId: res.data.data[0].id,
				  selectedDuration:res.data.data[0].id,
				  selectedContent:res.data.data[0].content||[],
				  selectChannel:res.data.data[0].channel||'base'
				})
				that.watchQuanyiContent()
			}
		})
	},
  // 选择有效期
  selectDuration: function(e) {
    const id = e.currentTarget.dataset.id;
    const selectedOption = this.data.durationOptions.find(item => item.id === id);
    
    this.setData({
      selectedDuration: id,
      selectedPrice: selectedOption.price,
      selectedDurationText: selectedOption.duration,
	  selectedPackageId: selectedOption.id,
	  selectedContent: selectedOption.content||[],
	  selectChannel:selectedOption.channel||'base'
    });
	this.watchQuanyiContent()
  },
  // 处理支付
  handlePayment: function() {
    // 这里应该是调用支付接口
    // 模拟支付成功
	//判断是否是续期  并且续费身份一致
	if(this.data.nowChannel != this.data.selectChannel && this.data.is_vip == 1){
		wx.showToast({ title: '您当前的会员身份与会员码不符，请到期后继续操作', icon: 'none' })
		return false;
	}
	let that= this;
	if (!this.data.isAgreed) {
	    wx.showToast({
	      title: '请先阅读并同意协议',
	      icon: 'none'
	    });
	    return;
	  }
    wx.showLoading({
          title: '支付处理中...',
        });
        const orderData = {
          selectedPackageId: this.data.selectedPackageId,
          selectedPrice: this.data.selectedPrice,
          createTime: new Date().toISOString()
        };
        
        console.log('提交订单数据:', orderData);
        
        let jsonData = JSON.stringify(orderData);
        // todo 提交医护上门申请API调用
        app.util.request({
        	url: 'Familydoctor/placeorder',
        	data: jsonData,
        	method:'POST',
        	headers: {
        		'Content-Type': 'application/json',
        	},
        	success(res) {
				wx.hideLoading();
        		var order_id=res.data.data.order_id;
				  var pay_params=res.data.data.pay_params;
	  
				  wx.requestPayment({
					  'timeStamp': pay_params.timeStamp,
					  'nonceStr': pay_params.nonceStr,
					  'package': pay_params.package,
					  'signType': 'MD5',
					  'paySign': pay_params.paySign,
					  'success': function (resp) {
						 that.setData({
							vipNum:that.data.vipNum + Number(order_id),
							showSuccessPopup: true
						 });
					let aid = '';
					  if(!aid){
						  aid=wx.getStorageSync('VP_AID');
					  }
						 app.mdInit(function (cfg,mine,area) {
						 	self.setData({
						 		cfg: cfg,
						 		mine:mine,
								nowChannel:mine.channel,
								is_vip:mine.is_vip,
						 		area:area
						 	});
						 						 
						 },{
						 	aid:aid,
						 	fuid:'',
						 	stid:''
						 },true);
					  },
					  'fail': function (res) {
							wx.showToast({ title: '支付失败', icon: 'none' })
					  }
				  })
        	}
        })
  },

  // 关闭成功弹窗
  closeSuccessPopup: function() {
    this.setData({
      showSuccessPopup: false
    });
    
    // 返回上一页或跳转到会员中心
	wx.redirectTo({
		url: '/vp_pz/pages/familydoctor/index',
	});
  }
});